package Client.Dropbox

import Client.Dropbox.SystemCommands.SystemListener
import Client.Dropbox.Manager.FileManager
import Client.Dropbox.Communication.Communicator
import Client.Dropbox.Manager.BoxManager
import Client.Dropbox.Communication.UpdateNotifier
import scala.actors.remote.Node
import Client.TaggingSystem.TagManager

/**
 * Object in charge of initializing and running Dropbox Service
 */
object DropboxMain extends App{
  
  var communicator=null.asInstanceOf[Communicator]
  
  var boxManager=null.asInstanceOf[BoxManager]
  
  /**
   * Main method
   * @param args the arguments for the main method
   */
  override def main(args:Array[String]) {
    if (args!=null&&args.length>0&&args.apply(0)!=null&&args.apply(0).equals("stop"))
    {
      stop
      return
    }
    //initialize all saved data
    FileManager.init
    
    //retrieve ports and server IP address
    var port=FileManager.myPort
    var serv=FileManager.serv
    var servPort=FileManager.servPort
    
    TagManager.init(FileManager.tagger)

    //initialize and start listening to operating system
    val listenerT=new Thread (SystemListener)
    listenerT start()
    
    //initialize and start actor to respond to commands
    boxManager=new BoxManager
    boxManager.start
    
    //start listening to changes on the server
    UpdateNotifier.init(port, serv, servPort)
    
    //initialize and start system to notify the server of changes
    communicator=new Communicator (port, Node(serv, servPort))
    communicator.start
    
    println("Started running")
    
    //wait for threads
    listenerT.join
    UpdateNotifier.join
  }
  
  /**
   * Method for stopping running
   */
  def stop {
    //stop all threads and actors
    SystemListener.stopRunning
    boxManager ! "stop"
    UpdateNotifier.stopRunning
    communicator ! "stop"
    //save state for next time
    FileManager.saveFS
    println("Stopped running")
  }
}